<?php
class Listing_RestController extends Ac_Rest_Controller
{

    /**
        return one random listing
    */
    public function indexAction() {
           
        $max_count = Model_Listing::all(array('sa' => Model_Listing::STATUS_PUBLISHED))->count(); 

        $skip = rand(0, $max_count);
        $list = Model_Listing::all(array('status' => Model_Listing::STATUS_PUBLISHED))->skip($skip)->limit(1);
        $list->rewind();
        $ele = $list->current();

        $this->_helper->json(array((string)$ele->_id => $ele->exportRest()));
    }

    /**
        return one specific listing
    */
    public function getAction() 
    {
        $id_param   = $this->_request->getParam('id');
        if($id_param == 'featured') {
            return $this->featuredAction();
        }
        if($id_param == 'latest') {
            return $this->latestAction();
        }
        if($id_param == 'user') {
            return $this->userAction();
        }
        if($id_param == 'company') {
            return $this->companyAction();
        }

        $id = 'listing_'.$id_param;
        $cache = Zend_Registry::get('Zend_Cache');
        if ( ($res = $cache->load($id)) !== false ) {
            $this->_helper->json($res);
        }

        $ele  = Model_Listing::one(array('_id' => new MongoId($id_param)));
        if (empty($ele)) {
            $this->getResponse()->setHttpResponseCode(403);
            throw new Ac_Exception_MissingInformation('Ad not found');
        }

        $res = $ele->exportRest();
        $cache->save($res, $id);
        $this->_helper->json($res);
    }

    public function latestAction() 
    {
        $compressed = false;
        if (!empty($_GET['co'])) {
            $compressed = true;
            unset($_GET['co']);
        }
        $id = 'listing_latest_'.($compressed ? '1' : '0');
        $cache = Zend_Registry::get('Zend_Cache');
        if ( ($res = $cache->load($id)) !== false ) {
            //$this->_helper->json($res);
        }

        $page     = 1;
        $per_page = !empty($_GET['limit']) ? intval($_GET['limit']) : 30;
        if (!empty($_GET['pg'])) {
            $page = intval($_GET['pg']);
        }
        
        $skip = ($page - 1) * $per_page;

        $list  = Model_Listing::all(array('sa' => Model_Listing::STATUS_PUBLISHED, 'so'=> array('$ne'=>6)))->sort(array('p_dt' => -1))->limit($per_page)->skip($skip);
        $res = array();
        if($list->count() > 0 ) {
            foreach($list as $ele) {
                if (!empty($ele)) {
                    $tmp = $ele->exportRest($compressed);
                    if($compressed) {
                        $tmp['_simplified'] = true;
                    }
                    $res[] = $tmp;
                }
            }
        }
        $cache->save($res, $id);
        $this->_helper->json($res);
    }


    public function companyAction()
    {
        $page = 1;
        $per_page= 10;
        if (!empty($_GET['pg'])) {
            $page = intval($_GET['pg']);
        }
        $compressed = false;
        if (!empty($_GET['co'])) {
            $compressed = true;
            unset($_GET['co']);
        }

        $skip = ($page - 1) * $per_page;

        $list = Model_User::all(array('cid' => new MongoId($_GET['id'])));

        $list_user = array();

        foreach($list as $user) {
            $list_user[] = $user->_id;
        }
        $list  = Model_Listing::all(array('status' => Model_Listing::STATUS_PUBLISHED, 'so'=> array('$ne'=>6), 'us' => array('$in' => $list_user)))->skip($skip)->limit($per_page)->sort(array('p_dt' => -1));
        //echo $list->count();exit;
        $res = array();
        if($list->count() > 0 ) {
            foreach($list as $ele) {
                if (!empty($ele)) {
//                    $res[] = $ele->exportRest();
                    $tmp = $ele->exportRest($compressed);
                    if($compressed) {
                        $tmp['_simplified'] = true;
                    }
                    $res[] = $tmp;

                }
            }
        }
        $this->_helper->json($res);
    }
 
    public function userAction()
    {
        $page = 1;
        $per_page= 10;
        if (!empty($_GET['pg'])) {
            $page = intval($_GET['pg']);
        }

        $compressed = false;
        if (!empty($_GET['co'])) {
            $compressed = true;
            unset($_GET['co']);
        }

        $skip = ($page - 1) * $per_page;

        $list  = Model_Listing::all(array('status' => Model_Listing::STATUS_PUBLISHED, 'so'=> array('$ne'=>'1'), 'us' => new MongoId($_GET['id'])))->sort(array('p_dt' => 1))->skip($skip)->limit($per_page);
        $res = array();
        if($list->count() > 0 ) {
            foreach($list as $ele) {
                if (!empty($ele)) {
//                    $res[] = $ele->exportRest();
                    $tmp = $ele->exportRest($compressed);
                    if($compressed) {
                        $tmp['_simplified'] = true;
                    }
                    $res[] = $tmp;

                }
            }
        }
        $this->_helper->json($res);
    }
    
    public function featuredAction()
    {
        $compressed = false;
        if (!empty($_GET['co'])) {
            $compressed = true;
            unset($_GET['co']);
        }
        
        $id = 'listing_featured_'.($compressed ? '1' : '0');
        $cache = Zend_Registry::get('Zend_Cache');
        if ( ($res = $cache->load($id)) !== false ) {
        //    $this->_helper->json($res);
        }
    
        $tmp = array(
            new MongoId('4dfee2819ad3e56dd6ada01a'),
            new MongoId('4d00c48ee62d6cfc4caa4805'),
            new MongoId('4d00c48ee62d6cfc4c024805'),
            new MongoId('4dfc5b64fe0a93f64c9bb68c'),
            new MongoId('4dff211b9ad3e56dd6adb3d1'),
            new MongoId('4df8bb11fe0a93f64c9aa955'),
            new MongoId('4dfe7d1d9ad3e56dd6ad8292'),
            new MongoId('4dfde46d9ad3e56dd6ad5ad5'),
            new MongoId('4ddbccf7dcab9f1a7ce4f9be'),
            new MongoId('4dfc5ab3fe0a93f64c9bb652'),
            new MongoId('4dfbb551fe0a93f64c9b885f'),
            new MongoId('4dfbb51afe0a93f64c9b8856'),
            new MongoId('4dfb8eeffe0a93f64c9b7fe6'),
            new MongoId('4dfb5e1efe0a93f64c9b7243'),
            new MongoId('4dfb0d52fe0a93f64c9b591c'),
            new MongoId('4dfa62fafe0a93f64c9b29d1'),
            new MongoId('4dfa2d85fe0a93f64c9b1c3d'),
            new MongoId('4df9f1c4fe0a93f64c9b08dd'),
            new MongoId('4df99d30fe0a93f64c9aeae4'),
            new MongoId('4df3508afe0a93f64c99119b'),
        );
        $res = array();
/*
        foreach($tmp as $idl) {
            $ele  = Model_Listing::find($idl);
            if (!empty($ele)) {
                $res[] = $ele->exportRest();
            }
        }
*/

        foreach($tmp as $idl) {
                $ele  = Model_Listing::find($idl);
                $tmp = $ele->exportRest($compressed);
                if($compressed) {
                    $tmp['_simplified'] = true;
                }
                $res[] = $tmp;
        }

        $cache->save($res, $id);
        $this->_helper->json($res);
        

    }

    public function photoAction() 
    {
       /* 
        var_dump($_POST);
        var_dump($_FILES);
        exit;
        */
         
        file_put_contents('/tmp/api-post-photo.txt', print_r($_SERVER, true).print_r($_POST, true). print_r($_FILES, true), FILE_APPEND);
        if (empty($_FILES)) {
            $this->getResponse()->setHttpResponseCode(406);
            throw new Ac_Exception_MissingInformation('No photos have been uploaded');            
        }
        if(empty($_POST['lid'])) {
            $this->getResponse()->setHttpResponseCode(406);
            throw new Ac_Exception_MissingInformation('Listing not provided');
        }
        
        $listing = Model_Listing::find($_POST['lid']);
        if(empty($listing)) {
            $this->getResponse()->setHttpResponseCode(406);
            throw new Ac_Exception_MissingInformation('Listing not found');
        }

        $_SERVER['HTTP_ADID'] = $listing;
        $_SERVER['NOT_JSON']  = 1;
        $res = Ac_Util::uploadListingPhotoProcess();

        $listing->forceSave();

        echo json_encode('ok');
        exit;
    }

    function putAction()
    {
        $id   = $this->_request->getParam('id');
        if($id == 'photo') {
            return $this->photoAction();
        }
        if($id == 'contact') {
            return $this->contactAction();
        }
        if ($id == 'start-import') {
            return $this->startImportAction();
        }
        if ($id == 'end-import') {
            return $this->endImportAction();
        }
    }

    public function startImportAction() 
    {
        $userid         = !empty($_POST['userid']) ? $_POST['userid'] : '';
        $private_key    = !empty($_POST['privatekey']) ? $_POST['privatekey'] : '';        
        $user           = Model_User::find($userid);

        var_dump($_POST, $user, $user->private_key, $private_key);

        if (!empty($private_key) && $user->private_key != $private_key) {
            $this->getResponse()->setHttpResponseCode(403);
            throw new Ac_Exception_MissingInformation('1 Invalid private key');
        }
        //update all listings to remove current transaction
        Model_Listing::update(array('us' => $user->_id), array('$unset' => array('process' => 1)), array('multiple' => true, 'safe' => true));
        Model_Listing::update(array('us' => $user->_id, 'sa' => Model_listing::STATUS_PUBLISHED), array('$set' => array('process' => 0)), array('multiple' => true, 'safe' => true));
    }

    
    public function endImportAction()
    {
        $userid         = !empty($_POST['userid']) ? $_POST['userid'] : '';
        $private_key    = !empty($_POST['privatekey']) ? $_POST['privatekey'] : '';
        $user           = Model_User::find($userid);

        if (!empty($private_key) && $user->private_key != $private_key) {
            $this->getResponse()->setHttpResponseCode(403);
            throw new Ac_Exception_MissingInformation('2 Invalid private key');
        }

        //update all listings to remove current transaction
        Model_Listing::update(array('us' => $user->_id, 'process' => 0, array('$set' => array('status' => Model_Listing::STATUS_DELETED))), array('multiple' => true, 'safe' => true));
        Model_Listing::update(array('us' => $user->_id), array('$unset' => array('process' => 1)), array('multiple' =>true, 'safe'=>true));

        //re index
        $list  = Model_Listing::all(array('us' => $user->_id));
        foreach($list as $obj) {
            $obj->rand = rand(1, 10000);
            $obj->save(); 
        }
    }


    public function contactAction() 
    {
        file_put_contents('/tmp/api-send-message.txt', print_r($_POST, true), FILE_APPEND);

        $message        = !empty($_POST['message']) ? $_POST['message'] : '';
        $phone          = !empty($_POST['phone']) ? $_POST['phone'] : '';
        $email          = !empty($_POST['email']) ? $_POST['email'] : '';
        $userid         = !empty($_POST['userid']) ? $_POST['userid'] : '';
        $sessionid      = !empty($_POST['sessionid']) ? $_POST['sessionid'] : '';
        $listingid      = !empty($_POST['listingid']) ? $_POST['listingid'] : '';
        
        $new = false;

        if(empty($userid) && empty($sessionid) && empty($email)) {
            $this->getResponse()->setHttpResponseCode(403);
            throw new Ac_Exception_MissingInformation('Missing identification');
        }

        if (empty($userid) && empty($email)) {
            $this->getResponse()->setHttpResponseCode(403);
            throw new Ac_Exception_MissingInformation('User is empty');
        }
        if (empty($sessionid) && empty($email)) {
            $this->getResponse()->setHttpResponseCode(403);
            throw new Ac_Exception_MissingInformation('SessionId is empty');
        }

        if (!empty($userid) && !empty($sessionid)) {
            $user = Model_User::find($userid);
            if (empty($user) || $user->session_id != $sessionid) {
                $this->getResponse()->setHttpResponseCode(403);
                throw new Ac_Exception_MissingInformation('SessionId or user invalid');
            }
        } elseif(!empty($email)) {
            $user = Model_User::one(array('email' => $email));
            if (empty($user)) {
                $new = true;
                $user           = new Model_User();
                $user->email    = $email;
                $user->phone    = $phone;
                $user->username = Model_User::generateUsername($email);
                $password = Model_User::getNewPassword();
                $user->password = Model_USer::generatePassword($password);
                $user->save();

                //$user = Model_User::create($data);
                $user_id = (string)$user->_id;
            }
        }
        if (!empty($user->status) && $user->status != Model_User::STATUS_ACTIVE) {
            $this->getResponse()->setHttpResponseCode(403);
            throw new Ac_Exception_MissingInformation('User not authorized');
        }

        $view    = Zend_Registry::get('Zend_View');
        $listing = Model_Listing::find($listingid);

        $subject_sender = $view->t('Your message was sent to [__1__ – Asiaclassified.com]', null, $listing->title);
        $message_sender = $message;
        $email_sender   = $email;
        $email_poster = $listing->user->email;

        //var_dump($_POST, $phone);exit;
        $un = explode('@', $email_sender);
        $subject = $view->t('__1__ sent you a message on Asiaclassified', null, $un[0]);

        //send the message to the sender
        if ($new) {
            Ac_Util::sendEmail($subject_sender, $message_sender, $email_sender, true, array('listing' => $listing, 'user' => $user, 'password' => $password), Ac_Mail::TEMPLATE_SENDMESSAGE_SENDER, AC_Mail::WEBMASTER);
        } else {
            Ac_Util::sendEmail($subject_sender, $message_sender, $email_sender, true, array('listing' => $listing), Ac_Mail::TEMPLATE_SENDMESSAGE_SENDER, AC_Mail::WEBMASTER);
        }

        //send the message to the poster
        Ac_Util::sendEmail($subject, $message_sender, $email_poster, true, array('listing' => $listing, 'email_sender' => $email_sender, 'phone_number' => $phone), Ac_Mail::TEMPLATE_SENDMESSAGE_POSTER, array('email' => $email_sender, 'name' => 'AsiaClassified'));

        echo $email_sender;

        echo json_encode("ok");exit;

    }

    public function postAction() 
    {
        file_put_contents('/tmp/api-post-listing.txt', print_r($_POST, true), FILE_APPEND);

        $title          = !empty($_POST['title']) ? $_POST['title'] : '';
        $description    = !empty($_POST['description']) ? $_POST['description'] : '';
        $category       = !empty($_POST['category']) ? $_POST['category'] : '';
        $userid         = !empty($_POST['userid']) ? (string)$_POST['userid'] : '';
        $username       = !empty($_POST['username']) ? $_POST['username'] : '';
        $sessionid      = !empty($_POST['sessionid']) ? $_POST['sessionid'] : '';
        $private_key    = !empty($_POST['privatekey']) ? $_POST['privatekey'] : '';
        $master_key     = !empty($_POST['masterkey']) ? $_POST['masterkey'] : '';
        $lang           = !empty($_POST['lang']) ? $_POST['lang'] : '';
        $nsme           = !empty($_POST['nsme']) ? $_POST['nsme'] : '';
        $district       = !empty($_POST['district']) ? $_POST['district'] : '';

        //validation
        if (empty($title)) {
            //echo 'title empty';exit;
            $this->getResponse()->setHttpResponseCode(403);
            throw new Ac_Exception_MissingInformation('Title is empty');
        }
        if (empty($category)) {
            //echo 'category empty';exit;
            $this->getResponse()->setHttpResponseCode(403);
            throw new Ac_Exception_MissingInformation('Category is empty');
        }
        if (empty($userid)) {
            //echo 'category empty';exit;
            $this->getResponse()->setHttpResponseCode(403);
            throw new Ac_Exception_MissingInformation('User is empty');
        }
        if (empty($lang) || !in_array($lang, array('en','tc', 'sc'))) {
            //echo 'category empty';exit;
            $this->getResponse()->setHttpResponseCode(403);
            throw new Ac_Exception_MissingInformation('Invalid language');
        }
        if (empty($sessionid) && empty($private_key) &&  empty($master_key)) {
            //echo 'category empty';exit;
            $this->getResponse()->setHttpResponseCode(403);
            throw new Ac_Exception_MissingInformation('SessionId is empty');
        }

        if (!empty($master_key) && $master_key != sha1(crc32('ioaiwdhzckjnh234das'))) {
            $this->getResponse()->setHttpResponseCode(403);
            throw new Ac_Exception_MissingInformation('Invalid master key: '. $master_key); 
        }

        $user = Model_User::find($userid);
        if(!empty($master_key) && empty($user)) {
            //find the user with id
            $user = Model_User::one(array('id' => $userid));
            if(empty($user)) {
                //user doesn't exists let's create one
                $user = new Model_User();
                $user->id = $userid;
                $user->sa = 1;
            }
            $user->un = $username;
            if (!empty($nsme)) {
                $user->nsme = (int)$nsme;
            }
            $user->save();
        }
        if (empty($user) || (empty($private_key) && $user->session_id != $sessionid)) {
            $this->getResponse()->setHttpResponseCode(403);
            throw new Ac_Exception_MissingInformation('SessionId or user invalid');
        }
/*
        if (empty($district) || ($location = Model_Location::find($district)) === false) {
            //echo 'category empty';exit;
            $this->getResponse()->setHttpResponseCode(403);
            throw new Ac_Exception_MissingInformation('District is empty');
        }
 */

        if (!empty($private_key) && empty($master_key) && $user->private_key != $private_key) {
            $this->getResponse()->setHttpResponseCode(403);
            throw new Ac_Exception_MissingInformation('3 Invalid private key');            
        }


        $cats = array();
        foreach((array) $category as $cat) {
            if(!empty($cat)) {
                $cats[] = new MongoId($cat);
            }
        }

        $classname = Model_Listing::getInstanceClassname($cats);

        if(!empty($private_key) || !empty($master_key)) {// API importer 
            $listing = $classname::one(array('pv' => $user->username, 'pvi' => $_POST['reference_id']));
        }
        if (empty($listing)) {
            $listing = new $classname;
        }
        if(empty($listing->at)) {
            if ($lang == 'en') {
                $listing->at = Model_Listing::ORIGINAL_LANGUAGE_EN;
            } elseif($lang == 'tc') {
                $listing->at = Model_Listing::ORIGINAL_LANGUAGE_TC;
            } elseif($lang == 'sc') {
                $listing->at = Model_Listing::ORIGINAL_LANGUAGE_SC;
            }
        }
        $listing->ca                     = $cats;
        $listing->{'tl_'.$lang}          = trim($title);
        $listing->{'cs_'.$lang}          = trim($description);
        //$listing->price                  = (float)$price;
        $listing->us                     = $user->_id;
        $listing->status                 = Model_Listing::STATUS_PUBLISHED;
        
        if(!empty($private_key) || !empty($master_key)) {// API importer 
            $provider_id       = !empty($_POST['reference_id']) ? $_POST['reference_id'] : '';
            $posted_at         = !empty($_POST['posted_at']) ? $_POST['posted_at'] : time();
            $url               = !empty($_POST['url']) ? $_POST['url'] : '';
            if (empty($listing->posted_at)) {
                if(is_numeric($posted_at)) {
                    $tmp = $posted_at;
                } else {
                    $tmp = strtotime($posted_at);
                }

                if (!empty($tmp)) {
                    $listing->posted_at  = $tmp;
                }
            }
            if (empty($listing->created_at)) {
                $listing->created_at  = time();
            }

            if (!empty($_POST['photos'])) {
                $listing->photos = array();
                foreach($_POST['photos'] as $k => $photo) {
                    if (!empty($photo)) {
                        $res = Ac_Util::downloadPhoto($listing->title, $k, $photo, true, $_POST['provider'], '', $listing->created_at);

                 /* 
                        var_dump($listing->title);
                        var_dump($k);
                        var_dump($listing->created_at);
                        var_dump($res);
                        //var_dump($listing->title);
                        var_dump($photo);
                        exit;
                  */    
                        $tmp = (array) $listing->photos;
                        if (array_search($res, $tmp) === false) {
                            if(!empty($res)) {
                                $tmp[] = $res;
                            } else {
                                $tmp[] = $photo;
                            }
                        }

                        $listing->photos = $tmp;
                    }
                }
                //echo "id: ". $listing->_id."\n";
                //print_r($listing->photos);
                //exit;
            }

            if (!empty($listing->photos)) {
                $tmp = $listing->photos;
                $tmp =  array_unique($tmp);
                $listing->photos = $tmp;
            }
                //print_r($listing->photos);
 
            $listing->rand = rand(0, 1000000);

            $listing->provider_id = $provider_id;
            $listing->provider    = $user->username;
            unset($listing->process);
            $listing->url         = $url;
        }

        $listing->processRestForm();

        $listing->forceSave();
        //$listing->save();

        

        $res = $listing->exportRest(true);
        
        //$this->getResponse()->setHttpResponseCode(201);
        //$this->_helper->json($res); 
        //header('Status: 200');
        echo json_encode(array('response' => $res));
        exit;
    }
}

